package c4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        ServerSocketChannel ssc = ServerSocketChannel.open();
//        设置服务端非阻塞
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
//            System.out.println("连接中");
            SocketChannel sc = ssc.accept();
            if(sc != null){
                System.out.println("连接成功"+ sc);
//                这也要设置非阻塞
                sc.configureBlocking(false);
                channels.add(sc);
            }
            for (SocketChannel channel: channels) {
                int read = channel.read(buffer);
                if(read > 0){
                    buffer.flip();
                    System.out.println(channel);
                    ByteBufferUtil.debugRead(buffer);
                    buffer.clear();
                }
            }
        }
    }
}
